package com.xinhe.web.service;

import org.springframework.stereotype.Service;

@Service
public class WeixinConfigService {

    /*private static final String CHARSET = "UTF-8";

    private static final String SUCCESS = "success";

    @Autowired
    private WeixinUtilBean weixinUtilBean;

    @Autowired
    private IValueConfigCache valueConfigCache;

    @Autowired
    private IWeixinConfigDao weixinConfigDao;

    @Autowired
    private WxConfigManager wxConfigManager;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;
    @Autowired
    private WeixinNotifyUtil weixinNotifyUtil;
    @Autowired
    private IWeixinUserDao weixinUserDao;
    @Autowired
    private IUserService userService;
    @Autowired(required = false)
    private IWeixinUserExtendService weixinUserExtendService;
    @Autowired
    private IValueConfigService valueConfigService;
    private static final String TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";

    @Transactional
    public void weixinUserAttentionNotify(Long configId) {
        log.info("微信服务号回调成功");
        String method = this.request.getMethod();
        if (method.equals("GET")) {

            String timestamp = this.request.getParameter("timestamp");
            String nonce = this.request.getParameter("nonce");
            String echostr = this.request.getParameter("echostr");
            String token = "xqg1024";
            List<String> params = new ArrayList<>();
            params.add(token);
            params.add(timestamp);
            params.add(nonce);

            params.sort(String::compareTo);



            respWeixinMessage(this.response, echostr);
        } else {

            Map<String, String> wxData = this.weixinNotifyUtil.getNotifyData();
            if (((String)wxData.get("MsgType")).equals("event"))
            {
                if (((String)wxData.get("Event")).equals("subscribe")) {

                    CloseableHttpClient httpClient = HttpClients.createDefault();
                    String openId = wxData.get("FromUserName");
                    String url = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN", new Object[] { this.weixinUtilBean
                            .getAccessToken(configId), openId });
                    HttpGet httpGet = new HttpGet(url);
                    String respJson = null;
                    try {
                        CloseableHttpResponse userHttpResp = httpClient.execute((HttpUriRequest)httpGet);
                        HttpEntity userEntity = userHttpResp.getEntity();
                        respJson = EntityUtils.toString(userEntity, "UTF-8");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    JSONObject jsonObject = JSONObject.fromObject(respJson);
                    log.info("关注服务号回调成功--->获取用户信息,{}" + jsonObject.toString());
                    WeixinLoginModel loginModel = new WeixinLoginModel();
                    loginModel.setConfigId(configId);
                    loginModel.setOpenid(jsonObject.optString("openid"));
                    loginModel.setUnionid(jsonObject.optString("unionid"));
                    loginModel.setIconPath(jsonObject.optString("headimgurl"));
                    loginModel.setNickname(jsonObject.optString("nickname"));
                    Long roleId = this.valueConfigCache.getLong("role_id_weixin_attention");

                    WeixinUser weixinUser = this.weixinUserDao.findOneByOpenid(jsonObject.optString("openid"));
                    if (weixinUser == null) {
                        weixinUser = new WeixinUser();
                        weixinUser.setOpenid(jsonObject.optString("openid"));
                        weixinUser.setUnionid(jsonObject.optString("unionid"));
                        weixinUser.setConfigId(configId);
                        List<WeixinUser> weixinUsers = this.weixinUserDao.findByUnionid(weixinUser.getUnionid());
                        if (CollectionUtils.isNotEmpty(weixinUsers)) {
                            WeixinUser otherWeixinUser = weixinUsers.get(0);
                            weixinUser.setUserId(otherWeixinUser.getUserId());
                        }
                        if (null == weixinUser.getUserId()) {
                            BeanResult<UserRegisterView> userResult = this.userService.registerUser(new UserRegisterModel(null, null, null, new Long[] { roleId }));
                            if (!userResult.getSuccess().booleanValue()) {
                                throw new BusinessException(userResult);
                            }
                            weixinUser.setUserId(((UserRegisterView)userResult.getItem()).getUserId());
                        }
                        if (this.weixinUserExtendService != null) {
                            this.weixinUserExtendService.saveWeixinUserExtend(weixinUser);
                        }
                        this.weixinUserDao.save((BaseEntityImpl)weixinUser);
                    }
                }
            }
            respWeixinMessage(this.response, "success");
        }
    }


    @Retryable(value = {BusinessException.class}, maxAttempts = 1, backoff = @Backoff(delay = 1L, multiplier = 0.0D))
    public BeanResult<String> sendTemplateMessage(SendTemplateMessageModel model) {
        BeanResult<String> result = new BeanResult();

        Long miniProgramId = this.valueConfigCache.getLong("weixin_config_id_mini_program");
        Long serviceId = this.valueConfigCache.getLong("weixin_config_id_service");

        WeixinUser weixinUser = this.weixinUserDao.findOneByConfigIdAndUserId(serviceId, model.getUserId());
        if (weixinUser == null) {
            log.error("用户{}未关注公众号", model.getUserId());
            return result;
        }

        WeixinConfig weixinConfig = (WeixinConfig)this.weixinConfigDao.findById(miniProgramId);
        String accessToken = this.weixinUtilBean.getAccessToken(serviceId);
        String url = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", new Object[] { accessToken });

        WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
        miniProgram.setAppid(weixinConfig.getAppId());
        miniProgram.setPagePath(model.getPagePath());






        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().templateId(model.getTemplateId()).url(url).toUser(weixinUser.getOpenid()).miniProgram(miniProgram).build();
        model.getData().forEach((k, v) -> paramWxMpTemplateMessage.addData(new WxMpTemplateData(k, v)));
        try {
            String msgId = this.wxConfigManager.getWxMpService().getTemplateMsgService().sendTemplateMsg(templateMessage);
            log.debug("公众号模板（跳转小程序）MSG_ID：{}", msgId);
            result.setItem(msgId);
        } catch (WxErrorException e) {
            log.error("公众号模板（跳转小程序）发送失败：{}", e.getMessage());
            throw new BusinessException(e.getMessage());
        }

        return result;
    }


    @Retryable(value = {BusinessException.class}, maxAttempts = 1, backoff = @Backoff(delay = 1L, multiplier = 0.0D))
    public BeanResult<String> sendTemplateMessageUrl(SendTemplateMessageUrlModel model) {
        BeanResult<String> result = new BeanResult();
        String accessToken = this.weixinUtilBean.getAccessToken(this.valueConfigCache.getLong("weixin_config_id_service"));
        String url = String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", new Object[] { accessToken });






        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().templateId(model.getTemplateId()).url(url).toUser(model.getOpenId()).url(model.getJumpUrl()).build();
        model.getData().forEach((k, v) -> paramWxMpTemplateMessage.addData(new WxMpTemplateData(k, v)));
        try {
            String msgId = this.wxConfigManager.getWxMpService().getTemplateMsgService().sendTemplateMsg(templateMessage);
            log.error("公众号模板（跳转网页）MSG_ID：{}", msgId);
            result.setItem(msgId);
        } catch (WxErrorException e) {
            log.error("公众号模板（跳转网页）发送失败：{}", e.getMessage());
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    @Recover
    private BeanResult<String> sendTemplateMessageRecover(BusinessException e, SendTemplateMessageModel model) {
        BeanResult<String> result = new BeanResult();
        JSONObject jsonObject = JSONObject.fromObject(e.getMessage());
        int errcode = jsonObject.getInt("errcode");
        if (errcode == 40001 || errcode == 42001) {


            this.weixinUtilBean.refreshWeixinFlag(this.valueConfigCache.getLong("weixin_config_id_service"));
            return sendTemplateMessage(model);
        }
        log.error("公众号模板（跳转小程序）方法重试失败：{}", e.getMessage());
        result.addErrorView(jsonObject.toString());
        return result;
    }

    @Recover
    private BeanResult<String> sendTemplateMessageUrlRecover(BusinessException e, SendTemplateMessageUrlModel model) {
        BeanResult<String> result = new BeanResult();
        JSONObject jsonObject = JSONObject.fromObject(e.getMessage());
        int errcode = jsonObject.getInt("errcode");
        if (errcode == 40001 || errcode == 42001) {


            this.weixinUtilBean.refreshWeixinFlag(this.valueConfigCache.getLong("weixin_config_id_service"));
            return sendTemplateMessageUrl(model);
        }
        log.error("公众号模板（跳转网页）方法重试失败：{}", e.getMessage());
        result.addErrorView(jsonObject.toString());
        return result;
    }

    private void respWeixinMessage(HttpServletResponse response, String message) {
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            servletOutputStream.write(message.getBytes());
            servletOutputStream.close();
        } catch (IOException var4) {
            var4.printStackTrace();
        }
    }*/
}
